# -*- coding: utf-8 -*-
'''
author:Cooper
date:2012.4.4
'''
import md5
import time
import requests
import MySQLdb
from Queue import Queue
from BeautifulSoup import BeautifulStoneSoup
import chardet

domain='http://gw.api.taobao.com/router/rest'
app_secret='dd547d6090fd8973346d41f704a173db'
dkey={
    'app_key':'12543465',
    'sign_method':'md5',
    'v':'2.0'}
mysql_host='localhost'
mysql_user='root'
mysql_pw=''

def getURL(params):
    timestamp=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
    params['timestamp']=timestamp
    for key in dkey:
        params[key]=dkey[key]
    s=[key+params[key] for key in params]
    s.sort()
    s=app_secret+''.join(s)+app_secret
    sign=md5.new(s).hexdigest().upper()
    url=domain+'?sign='+sign
    for para in params:
        url=url+'&%s=%s'%(para,params[para])
    return url

class Shop():
    def __init__(self,nick):
        self.nick=nick
    def getResponse(self,format='xml'):
        d=dict()
        d['method']='taobao.shop.get'
        d['format']=format
        if format not in ['xml','json']:d['format']='xml'
        d['nick']=self.nick
        d['fields']='sid,cid,title,nick,desc,bulletin,pic_path,created,modified'
        url=getURL(d)
        r=requests.request('GET',url)
        return r.content
    pass

class User():
    def __init__(self,nick):
        self.nick=nick
    def getResponse(self,format='xml'):
        d=dict()
        d['method']='taobao.user.get'
        d['format']=format
        if format not in ['xml','json']:d['format']='xml'
        d['nick']=self.nick
        d['fields']='user_id,uid,nick,sex,buyer_credit,seller_credit,location,\
        created,last_visit,birthday,type,status,alipay_no,alipay_account,\
        alipay_account,email,consumer_protection,alipay_bind'
        url=getURL(d)
        r=requests.request('GET',url)
        return r.content
    pass

class Users():
    def __init__(self,nicks):
        self.nicks=nicks
    def getResponse(self,format='xml'):
        d=dict()
        d['method']='taobao.users.get'
        d['format']=format
        if format not in ['xml','json']:d['format']='xml'
        d['nicks']=self.nicks
        d['fields']='user_id,uid,nick,sex,buyer_credit,seller_credit,location,\
        created,last_visit,birthday,type,status,alipay_no,alipay_account,\
        alipay_account,email,consumer_protection,alipay_bind'
        url=getURL(d)
        r=requests.request('GET',url)
        return r.content
    pass

class ItemCats():
    '''
    TaobaoAPI:taobao.itemcats.get
    Database:TMALL
    Table:ITEMCATS
    '''
    def __init__(self):
        pass
    def getAllCats(self):
        '''[cid,is_parent,name,parent_cid,sort_order]'''
        rl=list()
        from BeautifulSoup import BeautifulStoneSoup
        from Queue import Queue
        d=dict()
        d['method']='taobao.itemcats.get'
        d['format']='xml'
        d['field']=','.join(['cid','parent_cid','name','is_parent','status','sort_order'])
        q=Queue()
        q.put('0')
        while 1:
            if q.qsize()==0:
                break
            d['parent_cid']=q.get()
            print 'CID',d['parent_cid']
            url=getURL(d)
            r=requests.request('GET',url)
            soup=BeautifulStoneSoup(r.content,fromEncoding=r.encoding)
            for t in soup.findAll('item_cat'):
                tl=list()
                tl.append(t.find('cid').text.encode('utf-8'))
                tl.append(t.find('is_parent').text.encode('utf-8'))
                tl.append(t.find('name').text.encode('utf-8'))
                tl.append(t.find('parent_cid').text.encode('utf-8'))
                if t.find('sort_order'):
                    tl.append(t.find('sort_order').text.encode('utf-8'))
                else:
                    tl.append('0')
                rl.append(tl)
                if tl[1]=='true':
                    q.put(tl[0])
            pass
        return rl
    def SaveItemCats(cats):
        db=MySQLdb.connect(host=mysql_host,
            user=mysql_user,passwd=mysql_pw,
            db="tmall",charset="utf8")
        for t in ItemCats().getAllCats():
            print ','.join(t).decode('utf-8')
            cmdStr="INSERT IGNORE INTO ITEMCATS VALUES(%s,NOW())"%(','.join(["'%s'"%t2 for t2 in t]))
            db.query(cmdStr)
        db.commit()
        db.close()
        return True
    pass

class Items():
    def __init__(self):
        pass
    
    def getShopItems(self,nicks,format='xml'):
        rl=list()
        d=dict()
        d['method']='taobao.items.get'
        d['format']=format
        if format not in ['xml','json']:d['format']='xml'
        d['nicks']=nicks
        d['fields']=','.join(['detail_url','num_iid','title','nick','type',
            'volume','cid','pic_url','delist_time','location','price',
            'post_fee','score','second_kill'])
        d['page_no']='1'
        d['page_size']='100'
        d['order_by']='volume:desc'
        size=10**4
        while 1:
            if len(rl)>=size:
                break
            url=getURL(d)
            r=requests.request('GET',url)
            soup=BeautifulStoneSoup(r.content,fromEncoding=r.encoding)
            if size==10**4:size=__import__('string').atoi(soup.find('total_results').text)
            for item in soup.findAll('item'):
                row=[]
                for li in d['fields'].split(','):
                    if item.find(li):data=item.find(li).text
                    else:data=''
                    row.append(data.encode('utf-8'))
                rl.append(row)
            d['page_no']=str(__import__('string').atoi(d['page_no'])+1)
        print 'Success to get items...'
        return rl
    
    def writeShopItems(self,nicks):
        db=MySQLdb.connect(host=mysql_host,
            user=mysql_user,passwd=mysql_pw,
            db="tmall",charset="utf8")
        for item in self.getShopItems(nicks,'xml'):
            cmd="INSERT INTO ITEM VALUES(%s,NOW())"%','.join(["'%s'"%t for t in item])
            db.query(cmd)
        db.commit()
        db.close()
        pass
    
    def getResponse(self,format='xml'):
        pass
    pass

def getHotShopsData():
    shops=['莫海藻旗舰店','kimijanes旗舰店','百谷香旗舰店','艾曦服饰旗舰店','达蒙妮卡旗舰店',
        'bilunnu旗舰店','徽格儿旗舰店','amves旗舰店','sophy橡菲旗舰店','尚熙旗舰店',
        '彦怡裳旗舰店','闽绣旗舰店','e98旗舰店','符娇玲旗舰店','依嬅莎旗舰店',
        '韩帛伊品旗舰店','李羽竺服饰旗舰店','珍蕾迩服饰旗舰店','奈叶服饰旗舰店','伊姬卡服饰旗舰店']
    t=Items()
    for nick in shops:
        print nick.decode('utf-8')
        print time.asctime()
        t.writeShopItems('amves旗舰店')
        print time.asctime()
    pass

if __name__=='__main__':
    user=Users('osa品牌服饰旗舰店,geil旗舰店').getResponse()
    print user.decode('utf-8')
    #getHotShopsData()
    print 'the end...'
    pass
